<script setup lang="ts">
import { getAttrList } from "@/api/product/attr";
import { AttrInfo } from "@/api/product/attr/type";
import { getSpuImageList, getSpuSaleAttrList } from "@/api/product/spu";
import { SpuData, SpuImage, SpuSaleAttr } from "@/api/product/spu/type";
import { saveSku } from "@/api/product/sku";
import { SkuData, SkuImage } from "@/api/product/sku/type";
import { ElMessage, ElTable } from "element-plus";
import { ref } from "vue";
//Sku数据
const skuData = ref<SkuData>({
  skuName: "",
  price: 0,
  weight: "",
  skuDesc: "",
  category3Id: 0,
  spuId: 0,
  tmId: 0,
  skuDefaultImg: "",
  skuImageList: [],
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
});
//自定义事件
const emit = defineEmits(["changeScene"]);
//平台属性列表
const attrList = ref<AttrInfo[]>([]);
//SPU图片列表
const spuImageList = ref<SpuImage[]>([]);
//SKU图片列表
const skuImageList = ref<SkuImage[]>([]);
//SPU销售属性列表
const spuSaleAttrList = ref<SpuSaleAttr[]>([]);
//默认的图片
const defaultImg = ref<SpuImage>();
//table组件实例
const tableRef = ref<InstanceType<typeof ElTable>>();
//获取平台属性数据
const reqGetAttrList = async (
  c1Id: number,
  c2Id: number,
  c3Id: number | undefined,
) => {
  const res = await getAttrList(c1Id, c2Id, c3Id);
  if (res.code === 200) {
    attrList.value = res.data;
  }
};

//获取图片数据
const reqGetSpuImageList = async (spuId: number | undefined) => {
  const res = await getSpuImageList(spuId);
  if (res.code === 200) {
    spuImageList.value = res.data;
  }
};

//获取销售属性数据
const reqGetSpuSaleAttrList = async (spuId: number | undefined) => {
  const res = await getSpuSaleAttrList(spuId);
  if (res.code === 200) {
    spuSaleAttrList.value = res.data;
  }
};
//保存sku
const reqSaveSku = async () => {
  skuData.value.skuDefaultImg = defaultImg.value?.imgUrl || "";
  skuData.value.skuImageList = skuImageList.value;
  attrList.value.forEach((item) => {
    if (item.attrAndValue) {
      const [attrId, attrName, attrValueId, attrValueName] =
        item.attrAndValue.split(":");
      skuData.value.skuAttrValueList.push({
        attrId: parseInt(attrId),
        attrName: attrName,
        valueId: parseInt(attrValueId),
        valueName: attrValueName,
      });
    }
  });
  spuSaleAttrList.value.forEach((item) => {
    if (item.saleAttrAndValue) {
      const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] =
        item.saleAttrAndValue.split(":");
      skuData.value.skuSaleAttrValueList.push({
        saleAttrId: parseInt(saleAttrId),
        saleAttrName: saleAttrName,
        saleAttrValueId: parseInt(saleAttrValueId),
        saleAttrValueName: saleAttrValueName,
        spuId: skuData.value.spuId,
      });
    }
  });
  const res = await saveSku(skuData.value);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "添加SKU成功",
    });
    emit("changeScene", { params: "", num: 1 });
  } else {
    ElMessage({
      type: "error",
      message: "添加SPU失败",
    });
  }
};
//初始化页面数据
const initSkuData = (row: SpuData, c1Id: number, c2Id: number) => {
  //获取平台属性数据
  const c3Id = row.category3Id;
  reqGetAttrList(c1Id, c2Id, c3Id);
  reqGetSpuImageList(row.id);
  reqGetSpuSaleAttrList(row.id);
  //清空页面数据
  skuData.value = {
    skuName: "",
    price: null,
    weight: "",
    skuDesc: "",
    category3Id: row.category3Id,
    spuId: row.id,
    tmId: row.tmId,
    skuDefaultImg: "",
    skuImageList: [],
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
  };
};
//设置选中的图片
const handleSelectionChange = (val: SpuImage[]) => {
  skuImageList.value = val;
};
//设置默认图片
const setDefaultImg = (row: SpuImage) => {
  //按钮更换为success样式
  spuImageList.value.forEach((item) => {
    item.isDefault = "0";
  });
  row.isDefault = "1";
  tableRef.value?.toggleRowSelection(row, true);
  //将图片路径传递给父组件
  defaultImg.value = row;
};
//点击取消按钮，触发自定义事件，并传递参数
const cancel = () => {
  emit("changeScene", { params: "cancel", num: 1 });
};
defineExpose({
  initSkuData,
});
</script>

<template>
  <el-form label-width="100px">
    <el-form-item label="SKU名称">
      <el-input
        placeholder="请输入SKU名称"
        v-model="skuData.skuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="价格(元)">
      <el-input
        type="number"
        placeholder="请输入价格（元）"
        v-model="skuData.price"
      ></el-input>
    </el-form-item>
    <el-form-item label="重量(克)">
      <el-input
        type="number"
        placeholder="请输入重量（克）"
        v-model="skuData.weight"
      ></el-input>
    </el-form-item>
    <el-form-item label="SKU描述">
      <el-input
        type="textarea"
        placeholder="请输入SKU描述"
        v-model="skuData.skuDesc"
      ></el-input>
    </el-form-item>
    <el-form-item label="平台属性">
      <el-form :inline="true" label-width="180px">
        <el-form-item
          :label="attr.attrName"
          v-for="attr in attrList"
          :key="attr.id"
        >
          <el-select
            style="width: 240px; margin-bottom: 5px"
            v-model="attr.attrAndValue"
          >
            <el-option
              :label="attrValue.valueName"
              :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
              v-for="attrValue in attr.attrValueList"
              :key="attrValue.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-form :inline="true" label-width="80px">
        <el-form-item
          :label="saleAttr.saleAttrName"
          v-for="saleAttr in spuSaleAttrList"
          :key="saleAttr.id"
        >
          <el-select
            style="width: 240px; margin-bottom: 5px"
            v-model="saleAttr.saleAttrAndValue"
          >
            <el-option
              :label="saleAttrValue.saleAttrValueName"
              :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
              v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
              :key="saleAttrValue.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="图片列表">
      <el-table
        border
        ref="tableRef"
        style="width: 100%"
        :data="spuImageList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="图片">
          <template #default="{ row }">
            <img :src="row.imgUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column prop="imgName" label="名称" />
        <el-table-column prop="prop" label="操作">
          <template #default="{ row }">
            <el-button
              :type="row.isDefault === '1' ? 'success' : 'primary'"
              size="small"
              @click="setDefaultImg(row)"
              >设置默认</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="reqSaveSku">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped></style>
